package View;

import Controller.CarController;
import Controller.CustomerController;
import pojo.Car;
import pojo.Customer;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class Car_window extends Component {

    private JFrame frame = new JFrame("车辆管理和顾客管理界面");
    private JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);

    //车辆管理相关
    private JPanel vehiclemanagePanel = new JPanel();//车辆管理
    private JTable vehiclemanageTable = new JTable();
    private JLabel lblCarName =new JLabel("车辆品牌名称:");
    private JTextField vehicleSearchTextField = new JTextField(10);
    private JButton vehicleSearchButton = new JButton("查询车辆");
    private JButton vehicle_del = new JButton("删除");
    private JButton vehicle_add = new JButton("添加");
    private String[][] data ;
    private int del_vehicleid = -1;

    //顾客管理相关
    private JPanel customerPanel = new JPanel();//顾客管理
//    DefaultTableModel model = new DefaultTableModel()
    private JTable customerTable = new JTable();
    private JLabel lblCustomerName =new JLabel("顾客姓名:");
    private JTextField CustomerSearchTextField = new JTextField(10);
    private JButton CustomerSearchButton = new JButton("查询顾客");
    private JButton customer_del = new JButton("删除");
    private JButton customer_add = new JButton("添加");
    private String[][] customerdata ;
    private String[][] customer_alldata ;
    private int del_customerid = -1;

    // 控制
    private CarController carController = new CarController();
    private CustomerController customerController = new CustomerController();

    public Car_window() throws Exception {
        frameControl();
        close_openmain();
        getSelectDelId();

        //编辑功能
        customer_edit_action();
        car_edit_action();

    }

    public void customer_edit_action(){
        // 获取TableModel
        TableModel tableModel = customerTable.getModel();
        tableModel.addTableModelListener(e -> {
            // 处理表格模型的变化事件
            int firstRow = e.getFirstRow();
            int column = e.getColumn();
            if(column==0){
                //失败的信息
                JOptionPane.showMessageDialog(Car_window.this, "id无法编辑！", "失败", JOptionPane.ERROR_MESSAGE);
                return;
            }
            String old_data = customerdata[firstRow][column];
            String new_data = String.valueOf(tableModel.getValueAt(firstRow, column));
            if(!old_data.equals(new_data)){
                try {
                    //根据id删除这一条数据
                    int data_id = Integer.parseInt(customerdata[firstRow][0]);
                    customerController.deletecustomer(data_id);

                    //把新的数据进行插入
                    customerdata[firstRow][column] = new_data;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Customer customer = new Customer(1,customerdata[firstRow][1],customerdata[firstRow][2],customerdata[firstRow][3],sdf.parse(customerdata[firstRow][4]),Integer.parseInt(customerdata[firstRow][5]),Integer.parseInt(customerdata[firstRow][6]),customer_alldata[firstRow][8],Integer.parseInt(customerdata[firstRow][7]));
                    customerController.addcustomer(customer);

                    //刷新数据
                    getcustomerTableData();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        });
    }
    public void car_edit_action(){
        // 获取TableModel
        TableModel tableModel = vehiclemanageTable.getModel();
        tableModel.addTableModelListener(e -> {
            // 处理表格模型的变化事件
            int firstRow = e.getFirstRow();
            int column = e.getColumn();
            if(column==0){
                //失败的信息
                JOptionPane.showMessageDialog(Car_window.this, "id无法编辑！", "失败", JOptionPane.ERROR_MESSAGE);
                return;
            }
            String old_data = data[firstRow][column];
            String new_data = String.valueOf(tableModel.getValueAt(firstRow, column));
            if(!old_data.equals(new_data)){
                try {
                    //根据id删除这一条数据
                    int data_id = Integer.parseInt(data[firstRow][0]);
                    carController.deleteCar(data_id);

                    //把新的数据进行插入
                    data[firstRow][column] = new_data;
                    Car car = new Car(10,data[firstRow][1],data[firstRow][2],data[firstRow][3],data[firstRow][4],
                            Integer.parseInt(data[firstRow][5]),data[firstRow][6],data[firstRow][7],Integer.parseInt(data[firstRow][8]));
                    carController.addCar(car);

                    //刷新数据
                    getvehiclemanageTableData();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        });
    }



    //窗口关闭，打开main_window
    public void close_openmain(){
        // 设置窗口关闭操作为DO_NOTHING_ON_CLOSE
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        // 添加窗口关闭事件监听器
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                // 这里可以添加你的关闭逻辑
                frame.setVisible(false);
                new Main_window();
            }
        });

    }

    // 设置容器管理
    public void frameControl() throws Exception {
        // 设置底层容器和布局管理器
        frame.setSize(900, 700);
        frame.setLocation(600, 200);
        frame.setResizable(false);

        // 设置车辆浏览面板
        JScrollPane browseScrollPane = new JScrollPane(vehiclemanageTable);
        vehiclemanagePanel.setLayout(new BorderLayout());
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchPanel.add(vehicle_del,FlowLayout.LEFT);
        searchPanel.add(vehicle_add,FlowLayout.LEFT);
        searchPanel.add(lblCarName,FlowLayout.LEFT);
        searchPanel.add(vehicleSearchTextField,FlowLayout.CENTER);
        searchPanel.add(vehicleSearchButton,FlowLayout.RIGHT);
        vehiclemanagePanel.add(searchPanel, BorderLayout.NORTH);
        vehiclemanagePanel.add(browseScrollPane, BorderLayout.CENTER);

        // 设置顾客管理面板
        JScrollPane customerScrollPane = new JScrollPane(customerTable);
        customerPanel.setLayout(new BorderLayout());
        JPanel searchCustomerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchCustomerPanel.add(customer_del,FlowLayout.LEFT);
        searchCustomerPanel.add(customer_add,FlowLayout.LEFT);
        searchCustomerPanel.add(lblCustomerName,FlowLayout.LEFT);
        searchCustomerPanel.add(CustomerSearchTextField,FlowLayout.CENTER);
        searchCustomerPanel.add(CustomerSearchButton,FlowLayout.RIGHT);
        customerPanel.add(searchCustomerPanel, BorderLayout.NORTH);
        customerPanel.add(customerScrollPane, BorderLayout.CENTER);

        // 添加标签页
        tabbedPane.addTab("车辆管理", null, vehiclemanagePanel, null);
        tabbedPane.addTab("顾客管理", null, customerPanel, null);

        // 设置整体布局
        frame.setLayout(new BorderLayout());
        frame.add(tabbedPane, BorderLayout.CENTER);

        // 设置按钮事件处理
        setButtonActions();

        // 设置窗口可见性和关闭操作
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 初始时获取车辆信息和个人租车信息
        getvehiclemanageTableData();
        getcustomerTableData();
    }

    // 当选择了某一行的时候触发该事件
    public void getSelectDelId(){
                // 使用selection监听器来监听table的哪个条目被选中
        vehiclemanageTable.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {
                    @Override
                    public void valueChanged(ListSelectionEvent e) {
                        // 获取哪一行被选中了
                        int row = vehiclemanageTable.getSelectedRow();
                        if(row>=0){
                            del_vehicleid = Integer.parseInt(data[row][0]);
                        }else{
                         del_vehicleid = -1;
                        }
                        }
                });

        customerTable.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {
                    @Override
                    public void valueChanged(ListSelectionEvent e) {
                        // 获取哪一行被选中了
                        int row = customerTable.getSelectedRow();
                        if(row>=0){
                            del_customerid = Integer.parseInt(customerdata[row][0]);
                        }else{
                            del_customerid = -1;
                        }
                    }
                });
    }
    // 设置按钮事件处理
    public void setButtonActions() {
        //车辆品牌搜索按钮
        vehicleSearchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 执行查询车辆操作
                String searchText = vehicleSearchTextField.getText();
                if (searchText.equals("")) {
                    // 如果搜索框为空，显示所有车辆信息
                    try {
                        getvehiclemanageTableData();
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                } else {
                    // 否则，执行根据条件查询车辆信息
                    try {
                        findVehicle(searchText);
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        });
        //车辆删除按钮
        vehicle_del.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(del_vehicleid >= 0) {
                    try {
                        carController.deleteCar(del_vehicleid);
                        getvehiclemanageTableData();
                    } catch (Exception throwables) {
                        JOptionPane.showMessageDialog(Car_window.this, "该车辆有租赁记录，无法删除！", "失败", JOptionPane.ERROR_MESSAGE);
                    }
                }else{
                    JOptionPane.showMessageDialog(Car_window.this, "请选择要删除的车辆！", "失败", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        //车辆添加按钮
        vehicle_add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new CarAdd_window();
                frame.setVisible(false);
            }
        });

        //顾客按钮处理
        //顾客查询按钮
        CustomerSearchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 执行查询车辆操作
                String searchText = CustomerSearchTextField.getText();
                if (searchText.equals("")) {
                    // 如果搜索框为空，显示所有车辆信息
                    try {
                        getcustomerTableData();
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                } else {
                    // 否则，执行根据条件查询车辆信息
                    try {
                        findcustomer(searchText);
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        });
        //顾客删除
        customer_del.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(del_customerid >= 0) {
                    try {
                        customerController.deletecustomer(del_customerid);
                        getcustomerTableData();
                    } catch (Exception throwables) {
                        JOptionPane.showMessageDialog(Car_window.this, "该顾客有租赁记录，无法删除！", "失败", JOptionPane.ERROR_MESSAGE);
                    }
                }else{
                    JOptionPane.showMessageDialog(Car_window.this, "请选择要删除的顾客！", "失败", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        //顾客添加
        customer_add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               new Add_window();
               frame.setVisible(false);
            }
        });

    }

    // 获取所有车辆信息
    private void getvehiclemanageTableData() throws Exception {
        List<Car> carslist = carController.getAllCars();
        // 模拟获取车辆信息的数据
        String[] header = {"车辆ID", "车辆型号", "车辆品牌", "车牌号", "车辆状态", "租金", "燃油类型", "车辆颜色", "车辆里程数"};
        data = new String[carslist.size()][9];

        for (int i = 0; i < carslist.size(); i++) {
            Car car = carslist.get(i);
            data[i][0] = ""+car.getCar_id();
            data[i][1] = car.getModel();
            data[i][2] = car.getBrand();
            data[i][3] = car.getLicense_plate();
            data[i][4] = car.getStatus();
            data[i][5] = ""+car.getRental_rate();
            data[i][6] = car.getFuel_type();
            data[i][7] = car.getColor();
            data[i][8] = ""+car.getMileage();
        }
        vehiclemanageTable.setModel(new DefaultTableModel(data, header));
    }

    // 查询部分车辆信息
    private void findVehicle(String searchText) throws SQLException {
        List<Car> carslist = carController.getCarByBrand(searchText);
        // 模拟查询车辆信息的数据
        String[] header = {"车辆ID", "车辆型号", "车辆品牌", "车牌号", "车辆状态", "租金", "燃油类型", "车辆颜色", "车辆里程数"};
        String[][] data = new String[carslist.size()][9];

        for (int i = 0; i < carslist.size(); i++) {
            Car car = carslist.get(i);
            data[i][0] = ""+car.getCar_id();
            data[i][1] = car.getModel();
            data[i][2] = car.getBrand();
            data[i][3] = car.getLicense_plate();
            data[i][4] = car.getStatus();
            data[i][5] = ""+car.getRental_rate();
            data[i][6] = car.getFuel_type();
            data[i][7] = car.getColor();
            data[i][8] = ""+car.getMileage();
        }
        vehiclemanageTable.setModel(new DefaultTableModel(data, header));
    }

    // 获取所有顾客信息
    private void getcustomerTableData() throws Exception {
        List<Customer> customers = customerController.getAllCustomer();
        // 模拟获取个人信息的数据
        String[] header = {"顾客ID", "顾客姓名", "联系电话", "地址","注册时间","余额","驾驶证号码","租车数据"};
        customerdata = new String[customers.size()][8];
        customer_alldata = new String[customers.size()][9];

        for (int i = 0; i < customers.size(); i++) {
            Customer customer = customers.get(i);
            customer_alldata[i][0]= customerdata[i][0] = "" + customer.getCustomerId();
            customer_alldata[i][1]= customerdata[i][1] = customer.getName();
            customer_alldata[i][2]= customerdata[i][2] = customer.getContact();
            customer_alldata[i][3]= customerdata[i][3] = customer.getAddress();
            customer_alldata[i][4]= customerdata[i][4] = customer.getRegistrationDate().toString(); // 不能为空
            customer_alldata[i][5]= customerdata[i][5] = "" + customer.getLeftMoney();
            customer_alldata[i][6]= customerdata[i][6] = String.valueOf(customer.getDriverLicenseNumber()); // 根据实际情况获取字符串表示
            customer_alldata[i][7]= customerdata[i][7] = "" + customer.getRentCarNumber();
            customer_alldata[i][8]= customer.getPassword();
        }
        customerTable.setModel(new DefaultTableModel(customerdata, header));
    }
    // 查询部分顾客信息
    private void findcustomer(String searchText) throws SQLException {
        List<Customer> customers = customerController.getCarByBrand(searchText);
        // 模拟获取个人信息的数据
        String[] header = {"顾客ID", "顾客姓名", "联系电话", "地址","注册时间","余额","驾驶证号码","租车数据"};
        customerdata = new String[customers.size()][8];

        for (int i = 0; i < customers.size(); i++) {
            Customer customer = customers.get(i);
            customerdata[i][0] = "" + customer.getCustomerId();
            customerdata[i][1] = customer.getName();
            customerdata[i][2] = customer.getContact();
            customerdata[i][3] = customer.getAddress();
            customerdata[i][4] = customer.getRegistrationDate().toString(); // 不能为空
            customerdata[i][5] = "" + customer.getLeftMoney();
            customerdata[i][6] = String.valueOf(customer.getDriverLicenseNumber()); // 根据实际情况获取字符串表示
            customerdata[i][7] = "" + customer.getRentCarNumber();
        }
        customerTable.setModel(new DefaultTableModel(customerdata, header));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                Car_window car = new Car_window();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }

}


